import { useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";
import { AppSidebar } from "@/components/app-sidebar";
import { Breadcrumbs } from "@/components/bread-crumbs";
import { ModeToggle } from "@/components/nav/mode-toggle";
import { SidebarInset, SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import type { Session } from "@/lib/auth-client";
import { orgsQueryOptions, sessionQueryOptions } from "@/queries/auth";

export const Route = createFileRoute("/_app")({
  beforeLoad: async ({ context: { queryClient } }) => {
    const session = await queryClient.ensureQueryData(sessionQueryOptions);
    if (!session) throw redirect({ to: "/login" });
    const orgs = await queryClient.ensureQueryData(orgsQueryOptions(session.user.id));
    console.log(orgs);
    return { session, orgs };
  },
  component: RouteComponent,
});

function RouteComponent() {
  const { data: session } = useSuspenseQuery(sessionQueryOptions);
  const { data: orgs } = useSuspenseQuery(orgsQueryOptions(session?.user?.id as string));
  return (
    <SidebarProvider>
      <AppSidebar session={session as Session} orgs={orgs} />
      <SidebarInset className="flex flex-col gap-4 p-4 pl-2">
        <header className="flex shrink-0 items-center gap-2 transition-[width,height] ease-linear">
          <div className="flex w-full items-center justify-between gap-2">
            <div className="flex items-center gap-2">
              <SidebarTrigger />
              <Breadcrumbs />
            </div>
            <div className="flex items-center gap-2">
              <ModeToggle />
            </div>
          </div>
        </header>
        <div className="flex h-full w-full flex-1 flex-col gap-4">
          <Outlet />
        </div>
      </SidebarInset>
    </SidebarProvider>
  );
}
